package com.cf.api.controller;

import com.cf.api.model.ApiResp;
import com.md.common.utils.UUIDUitl;
import com.md.common.utils.date.DateUtil;
import com.md.common.utils.excel.POIExcelHandler;
import com.md.common.utils.excel.model.ExcelSheet;
import com.md.drcs.dicom.req.StudyCollectGroupReq;
import com.md.drcs.dicom.service.StudyCollectService;
import com.md.drcs.dicom.service.StudyService;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@CrossOrigin
@Controller
@RequestMapping("/study")
public class StudyController {

    private static final Logger LOGGER = LoggerFactory.getLogger(StudyController.class);

    @Value("${collect-export.folder}")
    private String exportFolder;

    // 延时任务线程池，主要用于删除临时文件
    private static ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(4);

    @Autowired
    private StudyCollectService studyCollectService;
    @Autowired
    private POIExcelHandler poiExcelHandler;
    @Autowired
    private StudyService studyService;

    @GetMapping("/collect/{year}-{month}")
    @ResponseBody
    public ApiResp collect(@PathVariable Integer year, @PathVariable Integer month) {
        return ApiResp.success(studyCollectService.getStudyCollect(year, month));
    }

    @GetMapping("/collect-group")
    @ResponseBody
    public ApiResp collectGroup(StudyCollectGroupReq req) {
        return ApiResp.success(studyCollectService.getStudyCollectGroup(req));
    }

    @GetMapping("/collect-export")
    public ResponseEntity<byte[]> collectExport(StudyCollectGroupReq req) throws IOException {
        ExcelSheet excelSheet = studyCollectService.exportStudyCollectGroup(req);
        String path = exportFolder + "/" + UUID.randomUUID().toString() + ".xlsx";
        File file = poiExcelHandler.writeExcel(path, excelSheet);
        String fileName = new String("云胶片统计.xlsx".getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        threadPool.schedule(() -> {
            boolean delete = file.delete();
            LOGGER.info("[download] delete tmp file: {} [{}]", file.getAbsolutePath(), delete);
        }, 180, TimeUnit.SECONDS);

        return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    }

    @GetMapping("/print-time")
    @ResponseBody
    public ApiResp printTime(String stuidInPacs) {
        LocalDateTime date = studyService.getPrintTime(stuidInPacs);
        if (date == null) {
            return ApiResp.success("该检查未打印胶片");
        }
        return ApiResp.success("", DateUtil.formaterLocalDateTime(date));
    }

}
